import React, { useState } from "react";
import {
  Card,
  Button,
  Space,
  Tag,
  Typography,
  InputNumber,
  Switch,
} from "antd";
import { useRequest } from "ahooks";
import { history } from "umi";

const { Text, Paragraph } = Typography;

// 模拟 API 请求
const fetchTime = (): Promise<{ time: string; timestamp: number }> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        time: new Date().toLocaleTimeString(),
        timestamp: Date.now(),
      });
    }, 500);
  });
};

const PollingPage: React.FC = () => {
  const [pollingInterval, setPollingInterval] = useState(2000);
  const [polling, setPolling] = useState(true);

  const { data, loading, error, run, cancel } = useRequest(fetchTime, {
    pollingInterval: polling ? pollingInterval : 0,
    pollingWhenHidden: false,
  });

  return (
    <div style={{ padding: "24px" }}>
      <Button
        onClick={() => history.push("/")}
        style={{ marginBottom: "16px" }}
      >
        返回首页
      </Button>

      <Card
        title="useRequest 轮询 (pollingInterval)"
        style={{ marginBottom: "16px" }}
      >
        <Paragraph>
          <Text strong>功能说明：</Text> 测试 pollingInterval
          参数，设置轮询间隔时间，自动重复请求。
        </Paragraph>

        <Space direction="vertical" style={{ width: "100%" }}>
          <div>
            <Text strong>状态：</Text>
            {loading && <Tag color="processing">加载中...</Tag>}
            {error && <Tag color="error">错误: {error.message}</Tag>}
            {data && <Tag color="success">成功</Tag>}
            {polling && <Tag color="blue">轮询中 ({pollingInterval}ms)</Tag>}
          </div>

          <Space>
            <Text>轮询开关：</Text>
            <Switch
              checked={polling}
              onChange={setPolling}
              checkedChildren="开启"
              unCheckedChildren="关闭"
            />
          </Space>

          <Space>
            <Text>轮询间隔 (ms)：</Text>
            <InputNumber
              min={1000}
              max={10000}
              step={500}
              value={pollingInterval}
              onChange={(value) => setPollingInterval(value || 2000)}
              disabled={!polling}
            />
          </Space>

          <Space>
            <Button type="primary" onClick={() => run()} loading={loading}>
              手动请求
            </Button>
            <Button onClick={cancel} disabled={!polling}>
              停止轮询
            </Button>
          </Space>

          {data && (
            <div>
              <Text strong>最新数据：</Text>
              <div style={{ marginTop: "8px" }}>
                <p>时间: {data.time}</p>
                <p>时间戳: {data.timestamp}</p>
              </div>
            </div>
          )}
        </Space>
      </Card>
    </div>
  );
};

export default PollingPage;
